

from playwright.sync_api import sync_playwright, Browser

from config.config import hidden_browser
from model.ProConfModel import ProConfModel
from service.KeepAliveService import get_storage_path_by_pro, need_login
from service.LogService import add_log
from service.ServiceFactory import ServiceFactory
from tools.Result import error_result


def capture_request_headers(page):
    def handle_request(request):
        print(f"URL: {request.url}")
        print(f"Headers: {request.headers}")
        print("-" * 80)
    page.on("request", handle_request)




def get_data(pro_type:int, detail_url:str,browser):
    pro_conf = ProConfModel.get_by_type(pro_type)
    print("SSSSSS11122222")
    context = create_undisplay_context(browser, pro_conf) if hidden_browser() else create_display_context(browser,
                                                                                                          pro_conf)
    try:
        service = ServiceFactory.get_service(pro_conf.server_name)
        result = service.execute(browser, context, pro_conf, detail_url)
    except TimeoutError:
        return error_result("请求超时，请检查网络或重试")
    except RuntimeError as e:
        result = error_result(f"运行时错误: {e}")

    finally:
        context.close()

    add_log(pro_type, pro_conf.title, detail_url, result)
    return result
#有头模式
def create_display_context(browser: Browser,pro_config: ProConfModel):



    return browser.new_context(storage_state=None if need_login(pro_config) else get_storage_path_by_pro(pro_config))

#无头模式


def create_undisplay_context(browser: Browser,pro_config: ProConfModel):


    # 将user_agent移至上下文创建
    context = browser.new_context(
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
        device_scale_factor=1,
        timezone_id="Asia/Shanghai",
        locale="zh-CN",
        storage_state=None if need_login(pro_config) else get_storage_path_by_pro(pro_config)
    )
    return  context
